from flask import render_template, current_app, session, request, g
from flask.json import jsonify

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


# 使用蓝图注册路由
@index_blu.route('/')
@user_login_data
def index():
    # 验证用户是否登录

    user = g.user

    # 22222获取点击排行的新闻数据
    news_list = None
    try:
        # 查询 新闻 按照点击量 降序
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # click_news_list = []
    # # 编列所有新闻 把里面的新闻对象转为字典
    # for news in news_list:
    #     click_news_list.append(news.to_basic_dict())

    # 3333 分类数据的获取
    # 3.1获取所有分类
    categories = Category.query.all()

    # 分类列表
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        'click_news_list': news_list,
        'categories_list': categories_list
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    """浏览器标签上显示的网站图标"""
    # current_app.send_static_file是返回静态文件的方法
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/newslist')
def get_news_list():
    """
    获取指定分类的新闻列表
    1. 获取参数
    2. 校验参数
    3. 查询数据
    4. 返回数据
    :return:
    """
    # 1. 获取参数
    category_id = request.args.get('cid', 1)  # 分类id
    page = request.args.get('page', 1)  # 第几页
    per_page = request.args.get('per_page', constants.HOME_PAGE_MAX_NEWS)  # 每页的数量

    # 2. 校验参数
    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 查询数据 分页
    filters = []

    if category_id != 1:
        # 数据库里没有1这个分类，这里加判断 除了1之外才添加条件
        filters.append(News.category_id == category_id)

    try:
        # *filters解包
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

        # 获取查询出来的数据 news_list有新闻对象
        news_list = pagination.items
        # 获取到总页数
        total_page = pagination.pages
        # 当前页对象
        current_page = pagination.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_li = []
    for news in news_list:
        news_li.append(news.to_basic_dict())

    ret = {
        "errno": RET.OK,
        "errmsg": "OK",
        "totalPage": total_page,
        "currentPage": current_page,
        "newsList": news_li,
        "cid": category_id
    }

    return jsonify(ret)
